'''
一些装饰性的api和处理数据api
'''
import base64
import io
import PySimpleGUI as sg
from PIL import Image
import paramiko

def title_bar(title, text_color, background_color):
    '''
    实现好看的title
    :param title:
    :param text_color:
    :param background_color:
    :return:
    '''
    bc = background_color
    tc = text_color
    font = 'Helvetica 12'

    return [sg.Col([[sg.T(title, text_color=tc, background_color=bc, font=font, grab=True)]], pad=(0, 0), background_color=bc),
            sg.Col([[sg.T('_', text_color=tc, background_color=bc, enable_events=True, font=font, key='-MINIMIZE-'), sg.Text('❎', text_color=tc, background_color=bc, font=font, enable_events=True, key='Exit')]], element_justification='r', key='-C-', grab=True,
                   pad=(0, 0), background_color=bc)]

## 装饰按钮
def GraphicButton(text:str, key:str, image_data):
    text = text.replace('_', ' ')
    button = sg.Button('', image_data=image_data, button_color=('white', '#F1F1F1'), font='Any 15', key=key,
                       border_width=1)
    text = sg.Text(text, font='Any 10', size=(15, 1), justification='center', )
    return sg.Column([[button], [text]], element_justification='c')

'''
将转换为字节并可选地调整作为文件或base64字节对象的图像的大小。  
转换成PNG格式的过程中，以便可以显示tkinter  
:param file_or_bytes:字符串文件名或bytes base64图像对象  
:type file_or_bytes: (Union[str, bytes])  
:参数resize:可选的新大小  
:type resize: (Tuple[int, int] or None)  
:return:(bytes)一个字节串对象  
: rtype:(字节)  
'''
def convert_to_bytes(file_or_bytes, resize=None):
    if isinstance(file_or_bytes, str):
        img = Image.open(file_or_bytes)
    else:
        try:
            img = Image.open(io.BytesIO(base64.b64decode(file_or_bytes)))
        except Exception as e:
            dataBytesIO = io.BytesIO(file_or_bytes)
            img = Image.open(dataBytesIO)

    cur_width, cur_height = img.size
    if resize:
        new_width, new_height = resize
        scale = min(new_height/cur_height, new_width/cur_width)
        img = img.resize((int(cur_width*scale), int(cur_height*scale)), Image.ANTIALIAS)
    with io.BytesIO() as bio:
        img.save(bio, format="PNG")
        del img
        return bio.getvalue()

'''
ssh链接小车
'''
def ssh_connect(ip,user,password):
    SSH_client = paramiko.SSHClient()
    SSH_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    re = SSH_client.connect(ip, 22, user,password)
    stdin, stdout, stderr = SSH_client.exec_command('ls')
    return stdout
